package com.iocup.keybastion.core.impl;


import com.iocup.keybastion.context.WebContextHolder;
import com.iocup.keybastion.core.HttpActionAdapter;
import com.iocup.keybastion.exception.AuthenticationException;
import com.iocup.keybastion.exception.AuthorizationException;
import com.pine.sunflower.core.model.CommonErrorCode;
import com.pine.sunflower.core.model.HttpStatus;
import com.pine.sunflower.core.model.Result;
import com.pine.sunflower.core.utils.JsonUtils;

/**
 * @author xyjxust
 * @create 2022/3/4 10:57
 **/
public class DefaultHttpActionAdapter implements HttpActionAdapter {

    @Override
    public Object adapt(Exception e, WebContextHolder webContextHolder) {
        if(e==null){
            return null;
        }
        int state;
        if (e instanceof AuthenticationException) {
            state = HttpStatus.UNAUTHENTICATION.getCode();
        } else  if (e instanceof AuthorizationException) {
            state = HttpStatus.UNAUTHORIZED.getCode();
        }
        else {
            state = HttpStatus.SYSTEM_ERROR.getCode();
        }
        webContextHolder.setResponseStatus(state);
        webContextHolder.setResponseContentType("application/json;charset=utf-8");
        /**
         * @todo 还未进行错误码处理
         */
        webContextHolder.responseOutput(JsonUtils.toString(Result.error(CommonErrorCode.SYSTEM_ERROR.getCode(),e.getMessage())));
        return null;
    }
}
